package nl.boektrust.btsoep.client;

import nl.boektrust.btsoep.shared.model.BTEntity;
import nl.boektrust.btsoep.shared.model.Person;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.objectify.Key;

public class EditMensDialog extends DialogBox implements ChangeHandler, KeyUpHandler, KeyDownHandler, ValueChangeHandler<String> {
	Person p;
	MensenPanel panel;
	PersistentServiceAsync persistentService;
	final TextBox nametb = new TextBox();
	final Image nameIcon = new Image();
	final Image identifierviafIcon = new Image();
	final Image urlIcon = new Image();
	final Button ok = new Button("OK");
	final TextBox urltb = new TextBox();
	final Anchor urlhyperlink = new Anchor();
	final Label urllabel = new Label("bv. http://www.google.com/");
	final Anchor namehyperlink = new Anchor();
	final Label viafLabel = new Label("identifier VIAF: ");
	final Label viaffeedbacklabel = new Label("bv. 32095668 of 4941285,121699107");
	final TextBox identifierdaitb = new TextBox();
	final TextBox identifierviaftb = new TextBox();
	final HorizontalPanel viafhPanel = new HorizontalPanel();

	
	
	public EditMensDialog(Person p, MensenPanel parentPanel) {
		persistentService = GWT.create(PersistentService.class);
		if (p == null) {
			p = new Person("", "");
			p.setId(new Integer(0).longValue());
		}

		// Set the dialog box's caption.
		setText("Bewerk gegevens...");

		// Enable animation.
		setAnimationEnabled(true);

		// Enable glass background.
		setGlassEnabled(true);

		nametb.addKeyUpHandler(this); 
		nametb.addKeyDownHandler(this); 
		nametb.addChangeHandler(this);
		nametb.addValueChangeHandler(this);
		nametb.setText(p.getName());
		ValueChangeEvent.fire(nametb, p.getName());

		final TextBox bornPlacetb = new TextBox();
		bornPlacetb.setText(p.getBirthPlace());
		final TextBox diedPlacetb = new TextBox();
		diedPlacetb.setText(p.getDeceasedPlace());		
		urltb.addValueChangeHandler(this);
		urltb.addKeyUpHandler(this);
		urltb.addKeyDownHandler(this);
		urltb.setText(p.getUrl());
		urltb.setWidth("40em");
		ValueChangeEvent.fire(urltb, p.getUrl());

		identifierdaitb.setText(p.getIdentifier_dai());
		identifierdaitb.addChangeHandler(this);
		identifierviaftb.addValueChangeHandler(this);
		identifierviaftb.addKeyUpHandler(this);
		identifierviaftb.addKeyDownHandler(this);
		//identifierviaftb.setText(p.getIdentifier_viaf());
		identifierviaftb.setText(p.viafToString());

		ValueChangeEvent.fire(identifierviaftb, p.viafToString());

		final TextArea biografischta = new TextArea();
		biografischta.setText(p.getBiographical());
		biografischta.setCharacterWidth(60);
		biografischta.setVisibleLines(20);
		final ListBox bornYearListBox = new ListBox();
		final ListBox diedYearListBox = new ListBox();
		final ListBox authorIdListBox = new ListBox();
		bornYearListBox.addItem("Onbekend");
		diedYearListBox.addItem("Nog niet gestorven");
		for (int i=1700; i<2010; i++) {
			bornYearListBox.addItem(new Integer(i).toString());
			diedYearListBox.addItem(new Integer(i).toString());
		}
		if (p.getBirthYear() == -1) {
			bornYearListBox.setSelectedIndex(0);
		} else {
			bornYearListBox.setSelectedIndex(1+(p.getBirthYear()-1900));
		}
		if (p.getDeceasedYear() == -1) {
			diedYearListBox.setSelectedIndex(0);
		} else {
			diedYearListBox.setSelectedIndex(1+(p.getDeceasedYear()-1900));
		}
		if (p.isDeceased() == false) {
			diedPlacetb.setEnabled(false);
		} else {
			diedPlacetb.setEnabled(true);
		}
		authorIdListBox.addItem("VIAF");
		authorIdListBox.addItem("btauthorid");
		authorIdListBox.addItem("CB id");
		// hPanel is the main panel 
		VerticalPanel vPanel = new VerticalPanel();
		setWidget(vPanel);

		int numRows = 9;
		//+ p.getIdentifiers().size() +1;
		int rowNum = 0;
		Grid g = new Grid(numRows,5);
		HorizontalPanel h = new HorizontalPanel();
		h.add(nametb);
		h.add(nameIcon);
		h.add(namehyperlink);
		g.setWidget(rowNum, 0, new Label("Naam:"));
		g.setWidget(rowNum, 1, h);
		rowNum++;
		g.setWidget(rowNum, 0, new Label("Geboren:"));
		g.setWidget(rowNum, 1, bornYearListBox);   
		rowNum++;

		g.setWidget(rowNum, 0, new Label("te:"));
		g.setWidget(rowNum, 1, bornPlacetb);
		rowNum++;
		g.setWidget(rowNum, 0, new Label("Gestorven:"));
		g.setWidget(rowNum, 1, diedYearListBox); 
		rowNum++;
		g.setWidget(rowNum, 0, new Label("te:"));
		g.setWidget(rowNum, 1, diedPlacetb);
		rowNum++;
		g.setWidget(rowNum, 0, new Label("URL:"));
		h = new HorizontalPanel();
		h.add(urltb);
		h.add(urlIcon);
		h.add(urllabel);
		h.add(urlhyperlink);
		g.setWidget(rowNum, 1, h);
		rowNum++;
		g.setWidget(rowNum, 0, new Label("identifier DAI:"));
		g.setWidget(rowNum, 1, identifierdaitb);
		rowNum++;
		h = new HorizontalPanel();
		h.add(identifierviaftb);
		h.add(identifierviafIcon);
		h.add(viaffeedbacklabel);
		h.add(viafhPanel);
		g.setWidget(rowNum, 1, h);
		viafLabel.setTitle("Het VIAF ID: \"32095668\" voor Marcel Moring. Als dezelfde auteur meerdere nummers heeft, scheidt met comma: \"4941285,121699107\" voor Harry Mulisch. Zie www.viaf.net.");
		g.setWidget(rowNum, 0, viafLabel);
		rowNum++;
		/*for (int i=0; i<p.getIdentifiers().size(); i++) {
			g.setWidget(rowNum, 0, new Label("Identifier:"));
			g.setWidget(rowNum, 1, authorIdListBox);
			TextBox identifierTb = new TextBox();
			g.setWidget(rowNum, 2, identifierTb);
			rowNum++;
		}
		
		g.setWidget(rowNum, 0, new Label("Identifier:"));
		g.setWidget(rowNum, 1, authorIdListBox);
		g.setWidget(rowNum, 2, new Label("Identifier:"));
		rowNum++;
		*/
		g.setWidget(rowNum, 0, new Label("Biografisch:"));
		g.setWidget(rowNum, 1, biografischta);
		
		HorizontalPanel buttonPanel = new HorizontalPanel();
		final Person pp = new Person();
		if (parentPanel == null) {
			System.out.println("parentPanel is null");
		}
		
		final MensenPanel mPanel = parentPanel;
		if (mPanel == null) {
			System.out.println("mPanel is null");
		}
		pp.setId(p.getId());
		this.validateInput();

		ok.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				pp.setName(nametb.getText());
				pp.parseViafString(identifierviaftb.getText());
				pp.setUrl(urltb.getText());
				pp.setIdentifier_dai(identifierdaitb.getText());
				pp.setBiographical(biografischta.getText());
				pp.setBirthPlace(bornPlacetb.getText());
				int bornYear = -1;
				String bornYearString =  bornYearListBox.getItemText(bornYearListBox.getSelectedIndex());
				if (bornYearString.equalsIgnoreCase("Onbekend")) {
					bornYear = -1;
				} else {
					bornYear = new Integer(bornYearString).intValue();
				}
				pp.setBirthYear(bornYear);
				pp.setDeceasedPlace(diedPlacetb.getText());
				int diedYear = -1;
				String diedYearString =  diedYearListBox.getItemText(diedYearListBox.getSelectedIndex());
				if (diedYearString.equalsIgnoreCase("Nog niet gestorven")) {
					diedYear = -1;
				} else {
					diedYear = new Integer(diedYearString).intValue();
				}
				pp.setDeceasedYear(diedYear);
				persistentService.persistPerson(pp, new AsyncCallback<Key<Person>>() {
					//		@Override
					public void onFailure(Throwable caught) {
					//	Log.error("EditMensDialog (person): onClick(): PersistentService RPC call failed " + caught);
					}

					//      @Override
					public void onSuccess(Key<Person> result) {
						if (mPanel != null) mPanel.loadData();
						//Log.debug("EditMensDialog (person): onClick(): PersistentService RPC call succeeded");

					}

				});
				EditMensDialog.this.hide();
			}
		});
		buttonPanel.add(ok);
		Button cancel = new Button("Annuleer");
		cancel.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				// force reload of data, even if nothing has changed, to ensure proper behavior of the row selection mechanism
				if (mPanel != null) mPanel.loadData();

				EditMensDialog.this.hide();
			}
		});
		buttonPanel.add(cancel);
		vPanel.add(g);
		vPanel.add(buttonPanel);
	}
	
	public EditMensDialog(MensenPanel parentPanel) {
		this(null, parentPanel);
	}
	
	public void onChange(ChangeEvent event)  {
		Widget sender =  (Widget) event.getSource();
		
	
	}
	
	public void onKeyUp(KeyUpEvent event) {
	    Widget sender = (Widget) event.getSource();
	    this.validateInput();
	    if (sender == nametb) {
	    }
	
	}
	
	public void onKeyDown(KeyDownEvent event) {
		Widget sender = (Widget) event.getSource();
	    if (sender == nametb) {
	    	namehyperlink.setEnabled(false);
	    	namehyperlink.setVisible(false);
	    }
	    if (sender == identifierviaftb) {
	    	viafhPanel.setVisible(false);
	    }
	    if (sender == urltb) {
	    	urlhyperlink.setEnabled(false);
	    	urlhyperlink.setVisible(false);
	    }
	
	}

	public void onValueChange(ValueChangeEvent<String> event) {
		// TODO Auto-generated method stub
		System.out.println("value change handler fired");
		Widget sender = (Widget) event.getSource();
		if (sender == nametb) {
			if (((TextBox)sender).getValue().length() > 3) {
				namehyperlink.setEnabled(true);
				namehyperlink.setVisible(true);
				namehyperlink.setText("(VIAF)");
				namehyperlink.setHref("http://www.viaf.net/viaf/search?query=local.names+all+\""+((TextBox)sender).getValue()+"\"&stylesheet=/viaf/xsl/results.xsl&sortKeys=holdingscount&maximumRecords=100");
				namehyperlink.setTarget("_base");
			} else {
				namehyperlink.setEnabled(false);
				//namehyperlink.setVisible(false);
			}
			
		}
		if (sender == urltb) {
			System.out.println("urltb received value change event");
			// rewrite to include http:// if it's not there yet			
			if (((TextBox)sender).getValue().length() > 3) {
				System.out.println("urltb has length > 3");

				if (((TextBox)sender).getValue().startsWith("http://")) {} else {
					((TextBox)sender).setValue("http://"+((TextBox)sender).getValue());
				}
				urlhyperlink.setEnabled(true);
				urlhyperlink.setVisible(true);
				urlhyperlink.setText("test "+((TextBox)sender).getValue()+" in nieuw window");
				urlhyperlink.setHref(((TextBox)sender).getValue());
				urlhyperlink.setTarget("_base");
				urllabel.setVisible(false);
			} else {
				System.out.println("urltb doesn't have length > 3");

				urlhyperlink.setEnabled(false);
				urlhyperlink.setVisible(false);
				urllabel.setVisible(true);

			}
			if (((TextBox)sender).getValue().length() > 150) {
				((TextBox)sender).setValue(((TextBox)sender).getValue().substring(0, 150));
			}
		}
		if (sender == identifierviaftb) {
			// rewrite to include http:// if it's not there yet			
			if (((TextBox)sender).getValue().length() > 3) {
				viafhPanel.setVisible(true);
				viaffeedbacklabel.setVisible(false);
				if (BTEntity.isViafStringParsable(((TextBox)sender).getValue())) {
					String[] substrings = ((TextBox)sender).getValue().split(",");
					for (int i=viafhPanel.getWidgetCount()-1; i>=0; i--) viafhPanel.remove(i);
					viafhPanel.add(new Label("Lookup (www.viaf.net/viaf/): "));
					for (String st :substrings) {
						Anchor link = new Anchor();
						link.setHref("http://www.viaf.net/viaf/"+st);
						link.setText(st);
						link.setTarget("_base");
						viafhPanel.add(link);
						viafhPanel.add(new HTML("&nbsp;&nbsp;"));
					}
				}
				
				

			} else {
				viafhPanel.setVisible(false);
				viaffeedbacklabel.setVisible(true);

			}
			if (((TextBox)sender).getValue().length() > 150) {
				((TextBox)sender).setValue(((TextBox)sender).getValue().substring(0, 150));
			}
		}
		this.validateInput();

	}

	private boolean validateInput() {
		ok.setEnabled(false);
		// validate name field
		if (nametb.getText().length() < 3) {
			nameIcon.setUrl(GWT.getModuleBaseURL()+"20-no.png");
			return false;
		} else {
			nameIcon.setUrl(GWT.getModuleBaseURL()+"19-check.png");
		}
		// validate url field
		if (urltb.getText().length() > 0) {
			urlIcon.setVisible(true);
			if (urltb.getText().length() < 3) {
				urlIcon.setUrl(GWT.getModuleBaseURL()+"20-no.png");
				return false;
			} else {
				urlIcon.setUrl(GWT.getModuleBaseURL()+"19-check.png");
			}
		} else {
			urlIcon.setVisible(false);
		}
		if (identifierviaftb.getText().length() > 0) {
			identifierviafIcon.setVisible(true);
			if (identifierviaftb.getText().length() < 3 || BTEntity.isViafStringParsable(identifierviaftb.getText()) == false) {
				identifierviafIcon.setUrl(GWT.getModuleBaseURL()+"20-no.png");
				return false;
			} else {
				identifierviafIcon.setUrl(GWT.getModuleBaseURL()+"19-check.png");
			}
		} else {
			identifierviafIcon.setVisible(false);
		}
		ok.setEnabled(true);
		return true;
		
	}
		


}


